package com.huifaapp.mall.selectImage;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ProgressBar;

import com.huifaapp.mall.R;
import com.huifaapp.mall.activity.BaseActivity;
import com.huifaapp.mall.selectImage.crop.CropImage;
import com.huifaapp.mall.selectImage.crop.CropImageView;


/**
 * 裁剪界面
 *
 */
@SuppressLint("HandlerLeak")
public class CropImageActivity extends BaseActivity implements OnClickListener {
	private CropImageView mImageView;
	private Bitmap mBitmap;

	private CropImage mCrop;

	private Button mSave;
	private Button mCancel, rotateLeft, rotateRight;
	private String mPath = "CropImageActivity";
	public int screenWidth = 0;
	public int screenHeight = 0;
	String mUpKey, mUrl;
	boolean maintainAspectRatio;// 是否保持长宽比
	private ProgressBar mProgressBar;

	public static final int SHOW_PROGRESS = 2000;

	public static final int REMOVE_PROGRESS = 2001;
	private Handler resetHandler, mHandler;
	private float mAspectRatio;
	public static final int RESCODE_PATH = 1;
	public static final int RESCODE_IM = 2;

	@Override
	protected int getLayoutId() {
		return R.layout.gl_modify_avatar;
	}
	@Override
	protected void initialize() {
		init();
	}
	@Override
	protected void initView() {

	}

	@Override
	protected void onStop() {
		super.onStop();
		if (mBitmap != null) {
			mBitmap = null;
		}
	}

	private void init() {
		mHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
			}
		};

		resetHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
					case SHOW_PROGRESS:
						mProgressBar.setVisibility(View.VISIBLE);
						break;
					case REMOVE_PROGRESS:
						mHandler.removeMessages(SHOW_PROGRESS);
						mProgressBar.setVisibility(View.INVISIBLE);
						break;
				}
			}
		};

		getWindowWH();
		mPath = getIntent().getStringExtra("path");
		maintainAspectRatio = getIntent().getBooleanExtra("maintainAspectRatio", true);
		mAspectRatio = (float) getIntent().getDoubleExtra("AspectRatio", 1.0f);
		mImageView = (CropImageView) findViewById(R.id.gl_modify_avatar_image);
		mSave = (Button) this.findViewById(R.id.gl_modify_avatar_upload);
		mCancel = (Button) this.findViewById(R.id.gl_modify_avatar_cancel);
		rotateLeft = (Button) this.findViewById(R.id.gl_modify_avatar_rotate_left);
		rotateRight = (Button) this.findViewById(R.id.gl_modify_avatar_rotate_right);
		mSave.setOnClickListener(this);
		mCancel.setOnClickListener(this);
		rotateLeft.setOnClickListener(this);
		rotateRight.setOnClickListener(this);
		try {
			mBitmap = createBitmap(mPath, screenWidth, screenHeight);
			if (mBitmap == null) {
				showMsg("没有找到图片!");
				finish();
			} else {
				resetImageView(mBitmap);
			}
		} catch (Exception e) {
			showMsg("没有找到图片!");
			finish();
		}
		addProgressbar();
	}

	/**
	 * 获取屏幕的高和宽
	 */
	private void getWindowWH() {
		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		screenWidth = dm.widthPixels;
		screenHeight = dm.heightPixels;
	}

	private void resetImageView(Bitmap b) {
		mImageView.clear();
		mImageView.setImageBitmap(b);
		mImageView.setImageBitmapResetBase(b, true);
		mCrop = new CropImage(this, mImageView, resetHandler);
		mCrop.maintainAspectRatio = maintainAspectRatio;
		mCrop.mAspectRatio = mAspectRatio;
		mCrop.crop(b);
	}

	@Override
	public void onBackPressed() {
		super.onBackPressed();
		finish();
	}

	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.gl_modify_avatar_cancel:
				finish();
				break;
			case R.id.gl_modify_avatar_upload:
				Intent data = new Intent();
				data.putExtra("path", mCrop.saveToLocal(mCrop.cropAndSave()));
				setResult(RESCODE_PATH, data);
				finish();
				break;
			case R.id.gl_modify_avatar_rotate_left:
				mCrop.startRotate(270.f);
				break;
			case R.id.gl_modify_avatar_rotate_right:
				mCrop.startRotate(90.f);
				break;

		}
	}


	protected void addProgressbar() {
		mProgressBar = new ProgressBar(this);
		FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		params.gravity = Gravity.CENTER;
		addContentView(mProgressBar, params);
		mProgressBar.setVisibility(View.INVISIBLE);
	}

	public Bitmap createBitmap(String path, int w, int h) {
		try {
			BitmapFactory.Options opts = new BitmapFactory.Options();
			opts.inJustDecodeBounds = true;
			// inJustDecodeBounds设为true时将不为图片分配内存。
			BitmapFactory.decodeFile(path, opts);
			int srcWidth = opts.outWidth;// 获取图片的原始宽度
			int srcHeight = opts.outHeight;// 获取图片原始高度
			int destWidth = 0;
			int destHeight = 0;
			// 缩放的比例
			double ratio = 0.0;
			if (srcWidth < w || srcHeight < h) {
				ratio = 0.0;
				destWidth = srcWidth;
				destHeight = srcHeight;
			} else if (srcWidth > srcHeight) {// 按比例计算缩放后的图片大小，maxLength是长或宽允许的最大长度
				ratio = (double) srcWidth / w;
				destWidth = w;
				destHeight = (int) (srcHeight / ratio);
			} else {
				ratio = (double) srcHeight / h;
				destHeight = h;
				destWidth = (int) (srcWidth / ratio);
			}
			BitmapFactory.Options newOpts = new BitmapFactory.Options();
			// 缩放的比例，缩放是很难按准备的比例进行缩放的，目前我只发现只能通过inSampleSize来进行缩放，其值表明缩放的倍数，SDK中建议其值是2的指数值
			newOpts.inSampleSize = (int) ratio + 1;
			// inJustDecodeBounds设为false表示把图片读进内存中
			newOpts.inJustDecodeBounds = false;
			// 设置大小，这个一般是不准确的，是以inSampleSize的为准，但是如果不设置却不能缩放
			newOpts.outHeight = destHeight;
			newOpts.outWidth = destWidth;
			return BitmapFactory.decodeFile(path, newOpts);
		} catch (Exception e) {
			return null;
		}
	}
}
